<template>
  <a-modal :width="1250" body-style="padding: 0 20px 20px" v-model:visible="showTransferDialog" title="仓内库存调拨" top="8vh" title-align="start" :footer="false" :mask-closable="false" @cancel="closedDialog">
    <a-tabs v-model:active-key="activeTab" @change="getInventoryList">
      <a-tab-pane v-for="item in warehouseList" :key="item.warehouseCode" :title="item.warehouseName" />
    </a-tabs>
    <div class="product-w flex" style="padding: 10px 0">
      <div class="product-con flex">
        <ImgPopover :src="getMainUrl()">
          <template #con>
            <a-image width="60" height="60" fit="contain" :src="getMainUrl()" />
          </template>
        </ImgPopover>
        <div style="margin: 0 40px 0 5px">
          <p>{{ currentItem.sku }}</p>
          <p>{{ currentItem.cateName }}</p>
        </div>
      </div>
      <a-button class="gray-outline" size="mini" @click="showTransferLog = true">查看仓内调拨记录</a-button>
    </div>
    <div class="table-w" style="height: calc(84vh - 200px); overflow: hidden">
      <a-table
        v-if="activeTab"
        class="table-normal-line"
        ref="tableRef"
        :data="inventoryList"
        :scroll="{
          y: '100%',
          w: '100%',
        }"
        size="mini"
        :summary="true"
        :pagination="false"
      >
        <template #columns>
          <a-table-column data-index="shopName" title="店铺" :width="120" fixed="left">
            <template #cell="{ record, rowIndex }">
              <div class="flex-c">
                <p>{{ record.shopName }}</p>
                <a-popover v-if="rowIndex == 0">
                  <template #content>
                    <p style="width: 300px">共享是指该库存可以用于任何店铺去发货，不受限制。关联真实店铺的只能用于当前店铺发货。</p>
                  </template>
                  <icon-question-circle style="margin-left: 5px" />
                </a-popover>
              </div>
            </template>
          </a-table-column>
          <a-table-column data-index="msku" title="MSKU" :width="100" fixed="left" />
          <a-table-column data-index="salesman" title="销售员" :width="70">
            <template #cell="{ record }">
              <p>{{ getSalesmans(record) }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="amtGoodLocked" title="已锁定库存" :width="50">
            <template #cell="{ record }">
              <p>{{ record.amtGoodLocked || record.amtGoodLocked === 0 ? record.amtGoodLocked : '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="amtGoodAvailable" title="良品可用数" :width="50">
            <template #cell="{ record }">
              <p>{{ record.amtGoodAvailable || record.amtGoodAvailable === 0 ? record.amtGoodAvailable : '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="amtDefectiveAvailable" title="次品数" :width="50">
            <template #cell="{ record }">
              <p>{{ record.amtDefectiveAvailable || record.amtDefectiveAvailable === 0 ? record.amtDefectiveAvailable : '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column title="调入/调出" :width="90">
            <template #cell="{ record }">
              <a-select size="small" style="width: 70px" v-model="record.transType">
                <a-option :value="1" label="调入" />
                <a-option v-if="record.amtGoodAvailable > 0" :value="-1" label="调出" />
              </a-select>
            </template>
          </a-table-column>
          <a-table-column title="目标" :width="300">
            <template #cell="{ record }">
              <div class="flex-c">
                <p style="width: 75px">{{ record.transType == 1 ? '从何处调入' : '调到哪里' }}</p>
                <a-select size="small" style="width: 210px" :trigger-props="{ autoFitPopupMinWidth: true }" v-model="record.targetInfo" value-key="id">
                  <template v-for="(item, i) in inventoryList" :key="i">
                    <a-option v-if="item.id != record.id && (record.transType == 1 ? item.amtGoodAvailable > 0 : true)" :value="item" :label="item.shopName" />
                  </template>
                </a-select>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="调拨数量" :width="140">
            <template #cell="{ record }">
              <a-input-number hide-button size="small" :min="1" :precision="0" v-model="record.transAmt" style="width: 120px" :placeholder="`最多可${record.transType == 1 ? '调入' : '调出'}${getMaxNum(record)}`" />
            </template>
          </a-table-column>
          <a-table-column title="单价" :width="80">
            <template #cell="{ record }">
              <p>￥{{ record.price }}</p>
            </template>
          </a-table-column>
          <a-table-column data-index="value" title="货值" :width="80">
            <template #cell="{ record }">
              <span>￥{{ record.inventoryValue }}</span>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="70">
            <template #cell="{ record }">
              <a-popconfirm content="请再次确认！" @ok="submitData(record)" type="error">
                <a-button type="text" :disabled="submitLoading">确认调拨</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
        <template #summary-cell="{ column, record }">
          <div v-if="['amtGoodLocked', 'amtGoodAvailable', 'amtDefectiveAvailable'].includes(column.dataIndex)">{{ record[column.dataIndex] }}</div>
          <div v-else-if="column.dataIndex == 'salesman'">合计</div>
        </template>
      </a-table>
      <div v-else>
        <a-empty description="该产品暂不存在库存~" />
      </div>
    </div>
  </a-modal>
  <!-- 调拨记录 -->
  <StockTransferLog v-if="showTransferLog" :isShow="showTransferLog" :warehouse="currentWarehouse" :currentItem="currentItem" @closed="showTransferLog = false" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { findReplenishTransList, replenishConfirmTrans } from '@/api/purchase'
  import { findWarehouseByInventory } from '@/api/inventory'
  import StockTransferLog from './stockTransferLog.vue'

  onMounted(() => {
    getWarehouseList()
  })

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => {},
    },
  })

  const showTransferDialog = ref(props.isShow)
  const submitLoading = ref(false)
  const showTransferLog = ref(false)
  const activeTab = ref()
  const warehouseList = ref<Array<any>>([])
  const inventoryList = ref<Array<any>>([])
  const isUpdate = ref(false)
  const currentWarehouse = ref<any>({})

  // 获取仓库列表
  async function getWarehouseList() {
    if (!props.currentItem.sku) return
    const res: any = await findWarehouseByInventory({
      sku: props.currentItem.sku,
      warehouseAttribute: 1,
    })
    warehouseList.value = res?.data || []
    activeTab.value = warehouseList.value[0]?.warehouseCode
    getInventoryList()
  }
  // 显示图片
  function getMainUrl() {
    return props.currentItem?.productImgs?.[0]
  }
  // 显示业务员
  function getSalesmans(row: any) {
    return row?.salesmans?.[0]?.salesmanName
  }
  // 最大调拨数量
  function getMaxNum(row: any) {
    return row.transType == -1 ? row.amtGoodAvailable || 0 : row.targetInfo?.amtGoodAvailable || 0
  }

  // 获取当前仓库库存列表
  async function getInventoryList() {
    if (!activeTab.value) return
    currentWarehouse.value = warehouseList.value.find((el: any) => el.warehouseCode == activeTab.value)
    const res: any = await findReplenishTransList({
      id: props.currentItem.id,
      warehouseCode: activeTab.value,
    })
    inventoryList.value = res?.data || []
    inventoryList.value.forEach((el: any) => {
      el.transType = el.amtGoodAvailable > 0 ? -1 : 1
      el.targetInfo = inventoryList.value.find((item: any) => {
        return item.id != el.id && (el.transType == 1 ? item.amtGoodAvailable > 0 : true)
      })
    })
  }

  // 关闭
  function closedDialog() {
    emit('closed')
    if (isUpdate.value) {
      emit('success')
    }
  }

  // 保存信息
  async function submitData(row: any) {
    if (!row.transAmt) {
      Message.error('请输入调拨数量')
      return
    }
    let maxNum = getMaxNum(row)
    if (row.transAmt > maxNum) {
      Message.error('调拨数量不能超过' + maxNum)
      return
    }
    let warehouse: any = warehouseList.value.find((el: any) => el.warehouseCode == activeTab.value)
    let params = {
      currentId: row.id,
      targetId: row.targetInfo?.id,
      transType: row.transType,
      transAmt: row.transAmt,
      warehouseCode: warehouse?.warehouseCode,
      warehouseName: warehouse?.warehouseName,
    }
    let res: any = await replenishConfirmTrans(params)
    if (!res) return
    Message.success('调拨成功')
    isUpdate.value = true
    getInventoryList()
  }
</script>
<style lang="less"></style>
